/**
 * 分页参数接口
 */
interface PaginationOptions {
  page?: number;
  pageSize?: number;
}

/**
 * 分页信息接口
 */
interface PaginationInfo {
  total: number;
  totalPages: number;
  currentPage: number;
  pageSize: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

/**
 * 分页响应接口
 */
export interface PaginatedResult<T> {
  data: T[];
  pagination: PaginationInfo;
}

/**
 * 通用分页函数（适用于数组分页，主要用于测试或非 DB 场景）
 */
export function paginateArray<T>(
  data: T[],
  { page = 1, pageSize = 10 }: PaginationOptions
): PaginatedResult<T> {
  const currentPage = Number(page);
  const limit = Number(pageSize);
  const startIndex = (currentPage - 1) * limit;
  const endIndex = startIndex + limit;
  const paginatedData = data.slice(startIndex, endIndex);

  return {
    data: paginatedData,
    pagination: {
      total: data.length,
      totalPages: Math.ceil(data.length / limit),
      currentPage,
      pageSize: limit,
      hasNextPage: endIndex < data.length,
      hasPrevPage: startIndex > 0,
    },
  };
}

/**
 * MongoDB 分页参数返回类型
 */
interface MongoPagination {
  limit: number;
  skip: number;
}

/**
 * 构建 MongoDB 分页参数
 */
export function getMongoPagination({
  page = 1,
  pageSize = 10,
}: PaginationOptions): MongoPagination {
  const currentPage = Number(page);
  const limit = Number(pageSize);
  const skip = (currentPage - 1) * limit;

  return {
    limit,
    skip,
  };
}

/**
 * 构建标准分页响应（用于 MongoDB 查询后的分页响应）
 */
export function buildPaginationResponse<T>(
  data: T[],
  total: number,
  { page = 1, pageSize = 10 }: PaginationOptions
): PaginatedResult<T> {
  const currentPage = Number(page);
  const limit = Number(pageSize);

  return {
    data,
    pagination: {
      total,
      totalPages: Math.ceil(total / limit),
      currentPage,
      pageSize: limit,
      hasNextPage: currentPage * limit < total,
      hasPrevPage: currentPage > 1,
    },
  };
}
